package com.familyaccount.servlet;

import com.familyaccount.model.User;
import com.familyaccount.service.UserService;
import com.familyaccount.util.EmailUtil;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.net.URLEncoder;

public class UserServlet extends HttpServlet {
    private UserService userService;

    @Override
    public void init() throws ServletException {
        userService = new UserService();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 调试日志输出
        System.out.println("UserServlet doGet: servletPath=" + request.getServletPath() + ", pathInfo=" + request.getPathInfo());
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            response.sendRedirect(request.getContextPath() + "/index.jsp");
            return;
        }
        User currentUser = (User) session.getAttribute("user");
        // 只有GOD或ADMIN能访问用户管理
        if (!(currentUser.isGod() || currentUser.isAdmin())) {
            response.sendRedirect(request.getContextPath() + "/?error=无权限访问用户管理。");
            return;
        }

        // 兜底：只允许 /users 或 /users/，其他一律重定向到 /users
        String servletPath = request.getServletPath();
        String pathInfo = request.getPathInfo();
        if (servletPath.startsWith("/users") && pathInfo != null && !pathInfo.equals("/") && !pathInfo.isEmpty()) {
            // 新增：如果是 /edit，直接跳转回 /users，防止空白页
            if ("/edit".equals(pathInfo)) {
                response.sendRedirect(request.getContextPath() + "/users");
                return;
            }
            String errorMsg = "无权限操作或页面不存在。";
            String redirectUrl = request.getContextPath() + "/users?error=" + URLEncoder.encode(errorMsg, "UTF-8");
            response.sendRedirect(redirectUrl);
            return;
        }

        try {
            if (pathInfo == null || pathInfo.equals("/")) {
                // List users
                handleListUsers(request, response, currentUser);
            } else {
                response.sendRedirect(request.getContextPath() + "/users?error=页面不存在。");
                return;
            }
        } catch (Exception e) {
            response.sendRedirect(request.getContextPath() + "/users?error=获取数据时发生错误，请稍后重试。");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        System.out.println("doPost: session(before get)=" + request.getSession(false));
        HttpSession session = request.getSession(false);
        System.out.println("doPost: session(after get)=" + session + ", user=" + (session != null ? session.getAttribute("user") : "null"));
        if (session == null || session.getAttribute("user") == null) {
            System.out.println("doPost: session或user为空，重定向index.jsp");
            response.sendRedirect(request.getContextPath() + "/index.jsp");
            return;
        }
        User currentUser = (User) session.getAttribute("user");
        // 只有GOD或ADMIN能操作用户管理
        if (!(currentUser.isGod() || currentUser.isAdmin())) {
            String errorMsg = "无权限操作用户管理。";
            response.sendRedirect(request.getContextPath() + "/?error=" + URLEncoder.encode(errorMsg, "UTF-8"));
            return;
        }
        // 删除提前return的servletPath/pathInfo判断
        // 只保留try语句块内的pathInfo分支判断
        String servletPath = request.getServletPath();
        String pathInfo = request.getPathInfo();
        try {
            if (pathInfo == null) {
                response.sendRedirect(request.getContextPath() + "/users?error=请求无效。");
                return;
            } else if (pathInfo.equals("/edit")) {
                System.out.println("pathInfo == /edit, 调用 handleEditUser");
                handleEditUser(request, response);
            } else if (pathInfo.equals("/delete")) {
                System.out.println("pathInfo == /delete, 调用 handleDeleteUser");
                handleDeleteUser(request, response, currentUser);
            } else if (pathInfo.equals("/reset-password")) {
                System.out.println("pathInfo == /reset-password, 调用 handleResetPassword");
                handleResetPassword(request, response);
            } else {
                System.out.println("pathInfo 其他, 跳转页面不存在");
                response.sendRedirect(request.getContextPath() + "/users?error=页面不存在。");
                return;
            }
        } catch (Exception e) {
            response.sendRedirect(request.getContextPath() + "/users?error=操作失败，请稍后重试。");
        }
    }

    private void handleListUsers(HttpServletRequest request, HttpServletResponse response, User currentUser) 
            throws ServletException, IOException, SQLException {
        List<User> users = userService.getAllUsers();
        request.setAttribute("users", users);
        request.setAttribute("currentUser", currentUser);
        String error = request.getParameter("error");
        if (error != null) {
            request.setAttribute("error", error);
        }
        request.getRequestDispatcher("/users.jsp").forward(request, response);
    }

    private void handleAddUser(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException, SQLException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        boolean isAdmin = "on".equals(request.getParameter("isAdmin"));
        String role = isAdmin ? "ADMIN" : "USER";

        // Check if username already exists
        if (userService.getUserByUsername(username) != null) {
            request.setAttribute("error", "用户名已存在。");
            request.getRequestDispatcher("/users.jsp").forward(request, response);
            return;
        }

        // Create new user
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setName(name);
        user.setEmail(email);
        user.setRole(role);

        if (userService.addUser(user)) {
            response.sendRedirect(request.getContextPath() + "/users");
        } else {
            request.setAttribute("error", "添加用户失败，请稍后重试。");
            request.getRequestDispatcher("/users.jsp").forward(request, response);
        }
    }

    private void handleEditUser(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException, SQLException {
        HttpSession session = request.getSession(false);
        User currentUser = (User) session.getAttribute("user");
        int userId = Integer.parseInt(request.getParameter("id"));
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String role = request.getParameter("role");
        String password = request.getParameter("password");

        User user = userService.getUserById(userId);
        if (user == null) {
            System.out.println("handleEditUser: 用户不存在，return");
            String errorMsg = "用户不存在。";
            response.sendRedirect(request.getContextPath() + "/users?error=" + URLEncoder.encode(errorMsg, "UTF-8"));
            return;
        }
        // 权限控制
        if (currentUser.isGod()) {
            System.out.println("handleEditUser: GOD分支，允许操作");
        } else if (currentUser.isAdmin()) {
            if (user.isGod() || user.isAdmin()) {
                System.out.println("handleEditUser: ADMIN分支，目标用户为GOD或ADMIN，return");
                String errorMsg = "无权操作超级管理员或其他管理员。";
                response.sendRedirect(request.getContextPath() + "/users?error=" + URLEncoder.encode(errorMsg, "UTF-8"));
                return;
            }
            if ("GOD".equals(role) || "ADMIN".equals(role)) {
                System.out.println("handleEditUser: ADMIN分支，试图将用户设置为GOD或ADMIN，return");
                String errorMsg = "无权将用户设置为超级管理员或管理员。";
                response.sendRedirect(request.getContextPath() + "/users?error=" + URLEncoder.encode(errorMsg, "UTF-8"));
                return;
            }
        } else {
            if (user.getId() != currentUser.getId()) {
                System.out.println("handleEditUser: USER分支，试图操作他人账户，return");
                String errorMsg = "无权操作他人账户。";
                response.sendRedirect(request.getContextPath() + "/users?error=" + URLEncoder.encode(errorMsg, "UTF-8"));
                return;
            }
            System.out.println("handleEditUser: USER分支，不能修改自己的角色");
            role = user.getRole();
        }
        // 其余情况允许
        user.setName(name);
        user.setEmail(email);
        user.setRole(role);

        boolean updateSuccess = userService.updateUser(user);
        System.out.println("handleEditUser: updateUser返回 " + updateSuccess);
        // 如果新密码不为空，更新密码
        if (password != null && !password.trim().isEmpty()) {
            updateSuccess = userService.updatePassword(userId, password) && updateSuccess;
            System.out.println("handleEditUser: updatePassword后 updateSuccess=" + updateSuccess);
        }

        if (updateSuccess) {
            System.out.println("handleEditUser: 更新成功，重定向到 /users");
            response.sendRedirect(request.getContextPath() + "/users");
        } else {
            System.out.println("handleEditUser: 更新失败，重定向到 /users?error=更新用户失败，请稍后重试。");
            response.sendRedirect(request.getContextPath() + "/users?error=" + URLEncoder.encode("更新用户失败，请稍后重试。", "UTF-8"));
        }
    }

    private void handleDeleteUser(HttpServletRequest request, HttpServletResponse response, User currentUser) 
            throws ServletException, IOException, SQLException {
        int userId = Integer.parseInt(request.getParameter("id"));
        User user = userService.getUserById(userId);
        if (user == null) {
            String errorMsg = "用户不存在。";
            response.sendRedirect(request.getContextPath() + "/users?error=" + URLEncoder.encode(errorMsg, "UTF-8"));
            return;
        }
        // Prevent self-deletion
        if (userId == currentUser.getId()) {
            String errorMsg = "不能删除当前登录的用户。";
            response.sendRedirect(request.getContextPath() + "/users?error=" + URLEncoder.encode(errorMsg, "UTF-8"));
            return;
        }
        // 权限控制
        if (user.getUsername().equals("admin")) {
            // 只有admin本人可以删除admin
            if (!currentUser.getUsername().equals("admin")) {
                String errorMsg = "无权删除admin账户。";
                response.sendRedirect(request.getContextPath() + "/users?error=" + URLEncoder.encode(errorMsg, "UTF-8"));
                return;
            }
        } else if (user.isAdmin()) {
            // 只有admin可以删除其他管理员
            if (!currentUser.getUsername().equals("admin")) {
                String errorMsg = "无权删除其他管理员账户。";
                response.sendRedirect(request.getContextPath() + "/users?error=" + URLEncoder.encode(errorMsg, "UTF-8"));
                return;
            }
        }
        if (userService.deleteUser(userId)) {
            response.sendRedirect(request.getContextPath() + "/users");
        } else {
            response.sendRedirect(request.getContextPath() + "/users?error=删除用户失败，请稍后重试。");
        }
    }

    private void handleResetPassword(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException, SQLException {
        int userId = Integer.parseInt(request.getParameter("id"));
        User user = userService.getUserById(userId);
        if (user == null) {
            String errorMsg = "用户不存在。";
            response.sendRedirect(request.getContextPath() + "/users?error=" + URLEncoder.encode(errorMsg, "UTF-8"));
            return;
        }
        // Generate new random password
        String newPassword = generateRandomPassword();
        String hashedPassword = newPassword;
        if (userService.updatePassword(userId, hashedPassword)) {
            // Send email with new password
            String subject = "密码重置通知";
            String content = String.format(
                "您好，%s\n\n您的密码已被重置。新密码是：%s\n\n请登录后及时修改密码。",
                user.getName(), newPassword
            );
            if (EmailUtil.sendEmail(user.getEmail(), subject, content)) {
                response.sendRedirect(request.getContextPath() + "/users");
            } else {
                userService.updatePassword(userId, user.getPassword());
                response.sendRedirect(request.getContextPath() + "/users?error=" + URLEncoder.encode("密码重置失败，邮件发送出错。", "UTF-8"));
            }
        } else {
            response.sendRedirect(request.getContextPath() + "/users?error=" + URLEncoder.encode("密码重置失败，请稍后重试。", "UTF-8"));
        }
    }

    // 添加本地生成随机密码的方法
    private String generateRandomPassword() {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";
        StringBuilder password = new StringBuilder();
        java.util.Random random = new java.util.Random();
        for (int i = 0; i < 8; i++) {
            password.append(chars.charAt(random.nextInt(chars.length())));
        }
        return password.toString();
    }
} 